<script setup>
import { ref, onBeforeUnmount } from 'vue'
import { LatLng } from '../boot/latlng.plugin' // 确保路径正确

// 响应式状态
const isListening = ref(false)
const processing = ref(false)
const nmeaData = ref('等待数据...')
const positionData = ref(null)
const errorMsg = ref('')

// 监听器引用
let nmeaListener = null
let positionListener = null

// 权限检查
const checkPermissions = async () => {
  try {
    const { location } = await LatLng.checkPermissions()
    if (location !== 'granted') {
      const result = await LatLng.requestPermissions()
      if (result.location !== 'granted') {
        throw new Error('MISSING_PERMISSION')
      }
    }
  } catch (error) {
    handleError(error)
    throw error
  }
}

// 启动监听
const startListening = async () => {
  if (isListening.value) return

  try {
    processing.value = true
    await checkPermissions()

    // 启动插件监听
    await LatLng.startListening()

    // 注册NMEA监听
    nmeaListener = await LatLng.addListener('nmeaUpdate', ({ raw, timestamp }) => {
      nmeaData.value = `${new Date(timestamp).toLocaleTimeString()}\t ${raw}`
    })

    // 注册位置更新监听
    positionListener = await LatLng.addListener('positionUpdate', (data) => {
      positionData.value = {
        lat: data.lat.toFixed(6),
        lng: data.lng.toFixed(6),
        accuracy: data.accuracy,
        timestamp: new Date(data.timestamp),
      }
    })

    isListening.value = true
    errorMsg.value = ''
  } catch (error) {
    handleError(error)
  } finally {
    processing.value = false
  }
}

// 停止监听
const stopListening = async () => {
  if (!isListening.value) return

  try {
    await LatLng.stopListening()
    nmeaListener?.remove()
    positionListener?.remove()
    isListening.value = false
    nmeaData.value = '监听已停止'
  } catch (error) {
    handleError(error)
  }
}

// 错误处理
const handleError = (error) => {
  errorMsg.value = error.message
  console.error('[GNSS Error]', error)

  if (error.message.includes('MISSING_PERMISSION')) {
    alert('需要位置权限，请前往应用设置开启')
  }
}

// 自动清理
onBeforeUnmount(async () => {
  await stopListening()
})
</script>

<template>
  <div class="gnss-container">
    <!-- 控制按钮 -->
    <q-btn
      :color="isListening ? 'negative' : 'positive'"
      :label="isListening ? '停止监听' : '开始监听'"
      @click="isListening ? stopListening() : startListening()"
      :loading="processing"
    />

    <!-- 位置数据显示 -->
    <div v-if="positionData" class="q-mt-md">
      <q-card>
        <q-card-section>
          <div class="text-h6">当前位置信息</div>
          <q-separator class="q-my-sm" />
          <div>纬度: {{ positionData.lat }}</div>
          <div>经度: {{ positionData.lng }}</div>
          <div>精度: {{ positionData.accuracy }}米</div>
          <div>时间: {{ positionData.timestamp.toLocaleTimeString() }}</div>
        </q-card-section>
      </q-card>
    </div>

    <!-- NMEA原始数据 -->
    <q-card class="q-mt-md">
      <q-card-section>
        <div class="text-h6">原始NMEA数据</div>
        <pre class="nmea-pre">{{ nmeaData }}</pre>
      </q-card-section>
    </q-card>

    <!-- 错误提示 -->
    <q-banner v-if="errorMsg" class="bg-red-2 text-red-10 q-mt-md">
      {{ errorMsg }}
    </q-banner>
  </div>
</template>

<style scoped>
.gnss-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.nmea-pre {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  max-height: 300px;
  overflow: auto;
  white-space: pre-wrap;
}
</style>
